const { Sequelize, DataTypes } = require('sequelize');
const config = require('../config/default').db_config;

/**
 * 初始化连接实例
 */
const sequelize = new Sequelize(config.database, config.user, config.password, {
  host: config.host,
  dialect: config.dialect,
  // 修正查询datetime字段的显示格式
  dialectOptions: {
    dateStrings: true,
    typeCast: true
  },
  // 改为标准时区
  timezone: '+08:00'
});

/**
 * 测试数据库连接
 */
const isConnection = async () => {
  try {
    await sequelize.authenticate();
    console.log('Connection has been established successfully.');
  } catch (error) {
    console.log('Unable to connect to the database:', error);
  }
};

// 关闭数据库连接
const close = async () => {
  await sequelize.close();
  console.log(`Connection has been closed.`);
};

module.exports = {
  sequelize,
  DataTypes,
  isConnection,
  close
};
